(function (angular) {
    'use strict';

    angular.module('ytong.services').factory('authorizationManager',authorizationManager);

    function authorizationManager(proxyService, $log, Constants, growl, $q, $state){

        var users = [];

        function loadUnauthorizedUsers(){

            proxyService.get(Constants.URLS.AUTHORIZATION_URL)
                .then(function(responseData){
                    $log.info("Unauthorized users retrieved successfully.");
                    users = responseData.users;
                }, function(responseData){
                    if(responseData.query_result == Constants.QUERY_RESULTS.NO_RESULTS){
                        users = [];
                        $log.info("No unauthorized users.");
                    }else {
                        $log.info("Failed retrieving unauthorized users from server: " + responseData.log_error);
                        growl.error("Failed retrieving unauthorized users");
                        users = [];
                    }
                });
        };

        function getUnauthorizedUsersCount(){
            return users.length;
        };

        function getUnauthorizedUsers(){
            return users;
        };

        function authorizeUser(id, role){
            var defer = $q.defer();

            proxyService.post(Constants.URLS.AUTHORIZATION_URL, {id: id, role: role})
                .then(function(){
                    $log.info("User " + id + " role updated successfuly.");
                    growl.success("User Authorized");
                    defer.resolve();
                }, function(){
                    growl.error("User authorization failed");
                    defer.reject();
                });

            return defer.promise;

        };

        //interface
        return{
            loadUnauthorizedUsers: loadUnauthorizedUsers,
            getUnauthorizedUsers: getUnauthorizedUsers,
            getUnauthorizedUsersCount: getUnauthorizedUsersCount,
            authorizeUser: authorizeUser
        }
    };

}(angular));